import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Form, Button, Input, DatePicker, InputNumber, Upload, Tag, Switch, message, Divider, Radio, Modal } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import OperaPrompt from '@/components/OperaPrompt'
import styles from './index.less'
import Selector from './selector'

import request from '@/utils/request';


const save = (props: any) => {
    const { match: { params: { couponId } } } = props

    const [visable, setVisable] = useState(false);
    const [goodsList, setGoodsList] = useState([])

    const [form] = Form.useForm()
    const [data, setData] = useState({
        couponType: 1,
        validType: 1,
        goodsScope: 1,
    })

    const selectFinish = (selectedGoodsList: any) => {
        const result = selectedGoodsList.map((item: any) => ({
            goods_id: item.id,
            goods_title: item.goods_title,
            goods_price: item.goods_price,
            total_stock: item.total_stock
        }))
        setGoodsList(result)
    }
    const handleUploadChange = (info: any): any => {
        let fileList = info.fileList;
        fileList = fileList.slice(-1);
        if (info.file.status === 'done') {
            message.success(`${info.file.name}文件上传成功`);
            fileList[0].url = fileList[0]['response']['data']['filePath'];
        }
        return fileList
    }

    const onFinish = (values: any) => {
        values['goods_ids'] = goodsList.map((item: any) => item.goods_id)
        if (values['goods_scope'] === 2) { //指定商品
            if (values['goods_ids'].length < 1) {
                message.warning("请至少选择一个商品")
                return
            }
        }
        values['valid_end_time'] = values['valid_end_time'] && values['valid_end_time'].format('YYYY-MM-DD HH:mm:ss');
        values['can_direct_fetch'] = values['can_direct_fetch'] === true ? 1 : 0;

        /*  */
        request(`/promote/coupon/0`, {
            method: 'POST',
            data: { ...values },
        }).then((result) => {
            message.success(result.message, 1, () => {

            })

            // getList()
        })

    };
    const closeModal = () => {
        setVisable(false);
    };

    useEffect(() => {
        if (couponId > 0) {
            request(`/promote/coupon/${couponId}`).then((result) => {
                const { couponData, goodsList } = result.data
                console.log(couponData, goodsList);
                let couponDetail = {
                    coupon_title: couponData.coupon_title,
                    coupon_type: couponData.coupon_type,
                    publish_num: couponData.publish_num,
                    max_fetch: couponData.max_fetch,
                    at_least: couponData.at_least,
                    can_direct_fetch: couponData === 1 ? true : false,
                    valid_type: couponData.valid_type,
                    goods_scope: couponData.goods_scope,

                    coupon_amount: couponData.amount,
                    discount: couponData.discount,
                    max_discount_amount: couponData.max_discount_amount,

                    // valid_end_time: couponData.valid_end_time,
                    valid_day_fetch: couponData.valid_day_fetch,
                }

                setData({
                    couponType: couponData.coupon_type,
                    validType: couponData.valid_type,
                    goodsScope: couponData.goods_scope,
                })

                if (couponData.goods_scope === 2) {
                    setGoodsList(goodsList.map((item: any) => ({
                        goods_id: item.id,
                        goods_title: item.goods_title,
                        goods_price: item.goods_price,
                        total_stock: item.total_stock
                    })))
                }

                form.setFieldsValue(couponDetail)
            })
        }
    }, [])

    const FullCut = (
        <Form.Item label="优惠券面额" extra="价格不能小于0，可保留两位小数" required >
            <Form.Item name="coupon_amount" noStyle rules={[{ required: true, message: '优惠券面额不能为空' }]}>
                <InputNumber />
            </Form.Item>
            <span style={{ paddingLeft: "8px" }}>元</span>
        </Form.Item>
    )
    const Discount = <>
        <Form.Item label="优惠券折扣" extra="优惠券折扣不能小于1折，且不可大于9.9折，可保留两位小数" required>
            <Form.Item noStyle name="discount" rules={[{ required: true, message: '优惠券折扣不能为空' }]}>
                <InputNumber />
            </Form.Item>
            <span style={{ paddingLeft: "8px" }}>折</span>
        </Form.Item>
        <Form.Item label="最多优惠">
            <Form.Item noStyle name="max_discount_amount">
                <InputNumber />
            </Form.Item>
            <span style={{ paddingLeft: "8px" }}>元</span>
        </Form.Item>
    </>

    return (
        <PageHeaderWrapper title={false} pageHeaderRender={() => { return '' }}>
            <Card bordered={false}>

                <OperaPrompt dataList={[
                    "有效期类型可选固定时间和自领取之日起",
                    "1、固定时间：选择结束日期，所有领取的优惠券有效期都截止在结束日期当天",
                    "2、自领取之日起：填写一个数字，表示从领取之日起有效期持续多少天",
                ]} />
                <div style={{ paddingTop: "12px" }}>
                    <Form
                        labelCol={{ span: 3 }}
                        wrapperCol={{ span: 13 }}
                        initialValues={{ coupon_type: 1, valid_type: 1, goods_scope: 1 }}
                        onFinish={onFinish}
                        form={form}
                    >
                        <Form.Item label="优惠券名称" name="coupon_title"
                            rules={[{ required: true, message: '优惠券名称不能为空' }]}>
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="优惠券类型"
                            name="coupon_type"
                        >
                            <Radio.Group onChange={(e) => setData({ ...data, couponType: e.target.value })}>
                                <Radio value={1}>满减</Radio>
                                <Radio value={2}>折扣</Radio>
                            </Radio.Group>
                        </Form.Item>

                        {data.couponType === 1 && FullCut}
                        {data.couponType === 2 && Discount}

                        <Divider />

                        <Form.Item label="发放数量" required>
                            <Form.Item name="publish_num" noStyle rules={[{ required: true, message: '发放数量不能为空' }]}>
                                <InputNumber />
                            </Form.Item>
                            <span style={{ paddingLeft: "8px" }}>张</span>
                        </Form.Item>

                        <Form.Item label="最大领取数量" required>
                            <Form.Item name="max_fetch" noStyle rules={[{ required: true, message: '最大领取数量不能为空' }]}>
                                <InputNumber />
                            </Form.Item>
                            <span style={{ paddingLeft: "8px" }}>张</span>
                        </Form.Item>

                        <Form.Item label="满多少元可以使用" extra="价格不能小于0，无门槛请设为0" required>
                            <Form.Item noStyle name="at_least" rules={[{ required: true, message: '多少元可以使用不能为空' }]}>
                                <InputNumber />
                            </Form.Item>
                            <span style={{ paddingLeft: "8px" }}>元</span>
                        </Form.Item>


                        <Form.Item label="优惠券图片" name="coupon_logo" valuePropName="fileList" getValueFromEvent={handleUploadChange} help="建议尺寸：325*95像素">
                            <Upload
                                action='http://127.0.0.1:8888/admin/tool/upload'
                                listType='picture'
                            >
                                <Button>
                                    <UploadOutlined /> Upload
                        </Button>
                            </Upload>
                        </Form.Item>

                        <Form.Item label="是否允许直接领取" name="can_direct_fetch" valuePropName="checked">
                            <Switch />
                        </Form.Item>

                        <Form.Item
                            label="有效期类型"
                            name="valid_type"
                        >
                            <Radio.Group onChange={(e) => setData({ ...data, validType: e.target.value })}>
                                <Radio value={1}>固定时间</Radio>
                                <Radio value={2}>领取之日起</Radio>
                            </Radio.Group>
                        </Form.Item>

                        {
                            data.validType === 1 &&
                            <Form.Item label="活动结束时间" required name="valid_end_time" rules={[{ required: true, message: '活动结束时间不能为空' }]}>
                                <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime />
                            </Form.Item>
                        }


                        {
                            data.validType === 2 &&
                            <Form.Item label="领取之日起" extra="不能小于0，且必须为整数" required>
                                <Form.Item noStyle name="valid_day_fetch" rules={[{ required: true, message: '领取之日起不能为空' }]}>
                                    <InputNumber />
                                </Form.Item>
                                <span style={{ paddingLeft: "8px" }}>天有效</span>
                            </Form.Item>
                        }

                        <Form.Item
                            label="活动商品"
                        >
                            <Form.Item noStyle name="goods_scope">
                                <Radio.Group onChange={(e) => setData({ ...data, goodsScope: e.target.value })}>
                                    <Radio value={1}>全部商品参与</Radio>
                                    <Radio value={2}>指定商品参与</Radio>
                                </Radio.Group>
                            </Form.Item>

                            <div style={data.goodsScope === 2 ? {} : { display: "none" }}>
                                <table className={styles.myTable}>
                                    <thead>
                                        <tr>
                                            <th>商品名称</th>
                                            <th>商品价格(元)</th>
                                            <th>库存</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {
                                            goodsList.map((item: any, inx: number) => <tr key={inx}>
                                                <td>{item.goods_title}</td>
                                                <td>￥{item.goods_price}</td>
                                                <td>{item.total_stock}</td>
                                                <td>
                                                    <Tag color="orange">删除</Tag>
                                                </td>
                                            </tr>)
                                        }
                                    </tbody>
                                </table>
                                <Button type="primary" onClick={() => { setVisable(true) }}>选择商品</Button>
                            </div>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 3 }}>
                            <Button type="primary" htmlType="submit">保存</Button>
                            <Button style={{ marginLeft: "8px" }} onClick={() => {
                                history.back()
                            }}>返回</Button>
                        </Form.Item>
                    </Form>
                </div>
            </Card>
            <Modal
                title="商品选择"
                width="60%"
                visible={visable}
                onCancel={closeModal}
                footer={null}
            >
                <Selector close={closeModal} idList={[]} selectFinish={selectFinish} />
            </Modal>

        </PageHeaderWrapper>
    );
};

export default save;